﻿using Bot.Domain.EndpointAPIResponseRecords;
using Bot.Domain.SessionChat;



using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Bot.Domain.Report
{
    public class UsageDetailsByTimeItem : BaseReportInfoItem
    {
        public int TotalCount { get; set; }
        public int MostTriggered { get; set; }
        public int SecondMostTriggered { get; set; }
        public int ThirdMostTriggered { get; set; }

        public override string GetValue(int i)
        {
            switch (i)
            {
                case 0:
                    return this.TotalCount.ToString();
                    break;
                case 1:
                    return this.MostTriggered.ToString();
                    break;
                case 2:
                    return this.SecondMostTriggered.ToString();
                    break;
                case 3:
                    return this.ThirdMostTriggered.ToString();
                    break;
                default:
                    return "";
            }
        }
    }
    public class UsageDetailsByTimeInfo : BaseReportInfo<UsageDetailsByTimeItem>
    {
        public int Total { get; set; }
        public List<UsageIntent> Top3UsedIntents { get; set; }

        [JsonIgnore]
        public override List<string> FieldList
        {
            get
            {
                return new List<string>() {
                    "Total Count",
                    "Most Triggered",
                    "Second Most Triggered",
                    "Third Most Triggered",
                };
            }
        }
        public override string GetValue(int i)
        {
            switch (i)
            {
                case 0:
                    return this.Total.ToString();
                case 1:
                    {
                        if(Top3UsedIntents!=null&& Top3UsedIntents.Count > 0)
                        {
                            return this.Top3UsedIntents[0].Count.ToString();
                        }

                        return "0";
                    }
                case 2:
                    {
                        if (Top3UsedIntents != null && Top3UsedIntents.Count > 1)
                        {
                            return this.Top3UsedIntents[1].Count.ToString();
                        }

                        return "0";
                    }
                case 3:
                    {
                        if (Top3UsedIntents != null && Top3UsedIntents.Count > 2)
                        {
                            return this.Top3UsedIntents[2].Count.ToString();
                        }

                        return "0";
                    }
                default:
                    return "";
            }
        }
    }
    public class UsageDetailsByTimeEntityInfo
    {
        public IList<GetUsageDetailsByTimeOutput> UsageDetailsByTimeEntityList { get; set; }
    }

    public class UsageDetailsByTimeWrap : BasicWrap<UsageDetailsByTimeItem, UsageDetailsByTimeInfo, UsageDetailsByTimeEntityInfo>
    {
        
        public static UsageDetailsByTimeInfo GetResponse(SearchCriteria search, UsageDetailsByTimeEntityInfo entityInfo, bool ifEncode = true)
        {
            UsageDetailsByTimeInfo result = new UsageDetailsByTimeInfo();
            //UTCToLocal(ref entityInfo);
            switch (search.dimensionType)
            {
                case EnumDimensionType.ByTime://by time
                //case EnumDimensionType.AllChannel:
                //case EnumDimensionType.DefaultChannel:
                //case EnumDimensionType.LivechatChannel:
                //case EnumDimensionType.FacebookChannel:
                //case EnumDimensionType.TwitterChannel:
                    result = GetInfoByTime(search, entityInfo, PushByTimeData, null, null);
                    break;
            }

            //watch.Stop();
            //System.Diagnostics.Debug.WriteLine("Calc Time: " + watch.Elapsed);

            return result;
        }

        //search the chat Source info for campaign by criteria
        private static UsageDetailsByTimeInfo GetResponseByDimension(SearchCriteria search, UsageDetailsByTimeEntityInfo entityInfo, bool ifEncode)
        {
            var result = new UsageDetailsByTimeInfo();
            //result.dataType = EnumReportDataType.DataByDimension;
            //List<EndpointAPIResponseRecordsOutputDto> data = entityInfo.ResponseEntityList.Where(a=>a.CodePlanId == int.Parse(search.filterStr)).ToList();

            //result.TotalResponse = data.Count;
            //if (search.dimensionType == EnumDimensionType.ByDepartment)
            //{
            //    result.TotalAgentOnly = data.Count(a=>a.ChatType== (int)EnumChatType.AgentOnly);
            //    result.TotalChatbotOnly = data.Count(a => a.ChatType == (int)EnumChatType.ChatbotOnly);
            //    result.TotalFromBotToAgent = data.Count(a => a.ChatType == (int)EnumChatType.ChatbotToAgent);
            //}

            //result.dataList = new List<ResponseItem>();

            //foreach (var item in data)
            //{
            //    var newItem = new ResponseItem();
            //    newItem.tableRowName = GetTableRowName(ifEncode, item.RequestTime);
            //    newItem.fieldId = item.FieldId;
            //    newItem.chatCount = item.Response;
            //    newItem.chatPercentage = CalcPercent(item.Response, result.totalChatCount);
            //    if (search.dimensionType == EnumDimensionType.ByDepartment)
            //    {
            //        newItem.fromChatButtonCount = item.ChatButtons;
            //        newItem.fromChatButtonPercentage = CalcPercent(item.ChatButtons, result.totalFromChatButtonCount);
            //        newItem.fromManuallyInvitationCount = item.ManuallyInvitations;
            //        newItem.fromManuallyInvitationPercentage = CalcPercent(item.ManuallyInvitations, result.totalFromManuallyInvitationCount);
            //        newItem.fromAutoInvitationCount = item.AutoInvitations;
            //        newItem.fromAutoInvitationPercentage = CalcPercent(item.AutoInvitations, result.totalFromAutoInvitationCount);
            //    }

            //    newItem.startTime = search.startDate.ToString();
            //    newItem.startTimeDate = search.startDate;
            //    newItem.endTime = search.endDate.ToString();
            //    newItem.endTimeDate = search.endDate;
            //    result.dataList.Add(newItem);
            //}

            //result.dataList = result.dataList.OrderByDescending(o => o.Time).ToList();
            return result;
        }

        private static UsageDetailsByTimeInfo PushByTimeData(UsageDetailsByTimeInfo result, UsageDetailsByTimeEntityInfo entityInfo, SearchCriteria search)
        {
            IEnumerable<GetUsageDetailsByTimeOutput> ResponseEntityList = entityInfo.UsageDetailsByTimeEntityList.OrderBy(c => c.CallTime);
            int lindex = 0;

            //top 3
            var totalCountByIntentList = ResponseEntityList.GroupBy(a => a.IntentName).Select(g => new
            {
                IntentName = g.Key,
                Total = g.Count()
            }).OrderByDescending(a => a.Total).Take(3).ToList();

            Guid operatorId = SessionHelper.GetSessionValue_CurrentOperatorId();
            foreach (var item in ResponseEntityList)
            {
                item.CallTime = DateTimeHelper.UtcToLocal(item.CallTime, operatorId);

                result.Total += 1;

                UsageDetailsByTimeItem UsageDetailsByTimeItem = result.dataList[lindex];
                while (item.CallTime >= UsageDetailsByTimeItem.endTimeDate && lindex < result.dataList.Count)
                {
                    lindex++;
                    UsageDetailsByTimeItem = result.dataList[lindex];
                }
                UsageDetailsByTimeItem.TotalCount+= 1;

                if (totalCountByIntentList != null)
                {
                    int topIndex = totalCountByIntentList.FindIndex(a => a.IntentName == item.IntentName);
                    if(topIndex == 0)
                    {
                        UsageDetailsByTimeItem.MostTriggered += 1;
                    }
                    else if (topIndex == 1)
                    {
                        UsageDetailsByTimeItem.SecondMostTriggered += 1;
                    }
                    else if (topIndex == 2)
                    {
                        UsageDetailsByTimeItem.ThirdMostTriggered += 1;
                    }
                }

            }
            result.Top3UsedIntents = new List<UsageIntent>();
            if (totalCountByIntentList != null)
            {
                foreach(var usedIntent in totalCountByIntentList)
                {
                    result.Top3UsedIntents.Add(new UsageIntent {
                        IntentName= usedIntent.IntentName,
                        Count= usedIntent.Total,
                    });
                }
            }
            result.dataList = result.dataList.Reverse().ToList();
            GetListTotal(ref result, search);
            return result;
        }

        private static void GetListTotal(ref UsageDetailsByTimeInfo result, SearchCriteria search)
        {
            double divNum = 0;
            if (search.timeUnit == EnumTimeIntervalType.Distribution24_7Hour)
            {
                divNum = GetWeeksInDateRange(search.startDate, search.endDate);
            }
            else if (search.timeUnit == EnumTimeIntervalType.Distribution48HalfHour)
            {
                divNum = GetDays(search.startDate, search.endDate);
            }           

            if (search.timeUnit == EnumTimeIntervalType.Distribution24_7Hour || search.timeUnit == EnumTimeIntervalType.Distribution48HalfHour)
            {

            }
        }

        #region export

        //search the New Export CSV Data for Chat Source Info by criteria
        public static NewExportCSVData GetExprotData(SearchCriteria search, UsageDetailsByTimeEntityInfo entityInfo)
        {
            UsageDetailsByTimeInfo info = GetResponse(search, entityInfo, false);
            NewExportCSVData result = new NewExportCSVData(string.Empty, new List<NewCSVColumn>(), new DataTable());
            switch (search.dimensionType)
            {
                case EnumDimensionType.ByTime://by time
                //case EnumDimensionType.AllChannel:
                //case EnumDimensionType.DefaultChannel:
                //case EnumDimensionType.LivechatChannel:
                //case EnumDimensionType.FacebookChannel:
                //case EnumDimensionType.TwitterChannel:
                    {
                        result = GetExprotCSVData(search, info, info.FieldList);
                        break;
                    }
                case EnumDimensionType.RequestPage:
                    {
                        result = GetExprotCSVData(search, info, new List<string>() { });
                        break;
                    }
            }
            return result;
        }

        #endregion

    }
}
